<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <div class="r-wrap">
      <div class="tabs-box">
        <a-button
            type="primary"
            class="tabs-item"
            v-for="(item, index) in tabList"
            :key="index"
            :ghost="tabKey !== item.key"
            @click="handleTabClick(item.key)"
        >
          {{ item.name }}
        </a-button>
      </div>
      <div class="r-content">
        <div v-if="tabKey === 'baseInfo'">
          <zh-form
              :span="6"
              ref="baseInfoFrom"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :model="formData"
          >
            <div style="padding: 15px 20px">
              <zh-row>
                <zh-input
                    prop="b0102"
                    :disabled="saveFlag"
                    type="text"
                    label="文物名称"
                    v-model="formData.b0102"
                ></zh-input>
                <zh-input
                    prop="b0122"
                    :disabled="saveFlag"
                    type="select"
                    :options="sqData"
                    :defaultFields="{ label: 'orgName', value: 'orgId' }"
                    label="县市区"
                    v-model="formData.b0122"
                    @change="handleChangeB0122"
                ></zh-input>
                <zh-input
                    prop="b0123"
                    :disabled="saveFlag"
                    type="select"
                    :options="jdDataArray"
                    :defaultFields="{ label: 'orgName', value: 'orgId' }"
                    label="乡镇街道"
                    v-model="formData.b0123"
                    @change="handleChangeB0123"
                ></zh-input>
                <zh-input
                    prop="b0104"
                    :disabled="saveFlag"
                    type="select"
                    :options="dictData.B0104"
                    :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
                    label="古系列类别"
                    v-model="formData.b0104"
                ></zh-input>
                <zh-input
                    prop="b0105"
                    :disabled="saveFlag"
                    type="select"
                    :options="dictData.B0105"
                    :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
                    label="文保级别"
                    v-model="formData.b0105"
                ></zh-input>
                <zh-input
                    prop="b0106"
                    :disabled="saveFlag"
                    type="select"
                    :options="dictData.B0106"
                    :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
                    label="建筑年代"
                    v-model="formData.b0106"
                ></zh-input>
                <zh-input
                    prop="b1102"
                    :disabled="saveFlag"
                    type="text"
                    label="保护范围面积(公顷)"
                    v-model="formData.b1102"
                ></zh-input>
                <zh-input
                    prop="b1103"
                    :disabled="saveFlag"
                    type="text"
                    label="核心保护范围面积(公顷)"
                    v-model="formData.b1103"
                ></zh-input>
                <zh-input
                    prop="b1104"
                    :disabled="saveFlag"
                    type="text"
                    label="建设控制地带面积(公顷)"
                    v-model="formData.b1104"
                ></zh-input>
                <zh-input
                    prop="b1105"
                    :disabled="saveFlag"
                    type="text"
                    label="公布时间"
                    v-model="formData.b1105"
                ></zh-input>
                <zh-input
                    prop="b1106"
                    :disabled="saveFlag"
                    type="select"
                    :options="dictData.B1106"
                    :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
                    label="标志牌设置情况"
                    v-model="formData.b1106"
                ></zh-input>
                <zh-input
                    prop="b1107"
                    :disabled="saveFlag"
                    type="text"
                    label="文物保护单位数量"
                    v-model="formData.b1107"
                ></zh-input>
                <zh-input
                    prop="b1108"
                    :disabled="saveFlag"
                    type="text"
                    label="历史建筑数量"
                    v-model="formData.b1108"
                ></zh-input>
                <zh-input
                    prop="b1109"
                    :disabled="saveFlag"
                    type="select"
                    :options="dictData.B1109"
                    :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
                    label="是否编制保护规划"
                    v-model="formData.b1109"
                ></zh-input>
                <zh-input
                    prop="b1110"
                    :disabled="saveFlag"
                    type="text"
                    label="规划编制时间"
                    v-model="formData.b1110"
                ></zh-input>
                <zh-input
                    prop="b1112"
                    :disabled="saveFlag"
                    type="text"
                    label="建筑面积(平方米)"
                    v-model="formData.b1112"
                ></zh-input>
                <zh-input
                    prop="b0113"
                    :disabled="saveFlag"
                    type="select"
                    :options="dictData.B1113"
                    :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
                    label="测绘建档情况"
                    v-model="formData.b0113"
                ></zh-input>
                <zh-input
                    prop="b1114"
                    :disabled="saveFlag"
                    type="text"
                    label="设立批复文件名"
                    v-model="formData.b1114"
                ></zh-input>
                <zh-input
                    prop="b1115"
                    :disabled="saveFlag"
                    type="text"
                    label="设立批复文号"
                    v-model="formData.b1115"
                ></zh-input>
                <zh-input
                    prop="b1116"
                    :disabled="saveFlag"
                    type="text"
                    label="批次"
                    v-model="formData.b1116"
                ></zh-input>
              </zh-row>
              <zh-row>
                <zh-input
                    prop="b1111"
                    :disabled="saveFlag"
                    type="textarea"
                    label="基本简介"
                    v-model="formData.b1111"
                    style="float: left"
                    :labelCol="{ span: 2 }"
                    :wrapperCol="{ span: 22 }"
                    :span="24"
                    :rows="3"
                ></zh-input>
              </zh-row>
              <zh-row>
                <zh-input
                    prop="b0109"
                    :disabled="saveFlag"
                    type="text"
                    label="地址"
                    :span="11"
                    :labelCol="{ span: 4 }"
                    :wrapperCol="{ span: 19 }"
                    v-model="formData.b0109"
                ></zh-input>
                <ep-button
                    style="margin-top: 5px ;margin-left: 10px"
                    type="primary"
                    size="small"
                    @click="queryTude('isClick')"
                >重新定位
                </ep-button>
                <zh-input
                    prop="b0111"
                    :disabled="saveFlag"
                    type="text"
                    label="经度"
                    :span="4"
                    v-model="formData.b0111"
                    @blur="pickUp"
                ></zh-input>
                <zh-input
                    prop="b0112"
                    :disabled="saveFlag"
                    type="text"
                    label="纬度"
                    :span="4"
                    v-model="formData.b0112"
                    @blur="pickUp"
                ></zh-input>
              </zh-row>
            </div>
          </zh-form>
        </div>
        <div class="map-box" v-show="tabKey === 'baseInfo'">
          <div id="gssp"></div>
          <div class="scale">
            <p @click="checkEnlarge">
              <span>+</span>
            </p>
            <p @click="checkNarrow">
              <span>-</span>
            </p>
          </div>
        </div>
        <div v-show="tabKey === 'mediaInfo'">
          <pointInfoMediaInfo ref="mediaInfoRef"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import zh_cn from "ant-design-vue/es/date-picker/locale/zh_CN";
import pointInfoBaseInfo from "@/pages/system/form/pointInfoBaseInfo";
import pointInfoMediaInfo from "@/pages/system/form/pointInfoMediaInfo";
import {getPointInfo, getSQAndJD} from "@/services/system/whdngxlApi";
import {getBatchDict,getDictCondition} from "@/services/system/api";
import AMapLoader from "@amap/amap-jsapi-loader";
import {gcj02towgs84} from "@/utils/wgs84";

export default {
  name: "streetBuildForm",
  components: {
    pointInfoBaseInfo,
    pointInfoMediaInfo,
  },
  props: {
    c0303: {
      required: false,
      type: String,
    },
    classify: {
      required: false,
      type: String,
    },
    b0101: {
      required: false,
      type: Number,
      default: () => {
        return null;
      },
    },
    // true 不可编辑 ,false 可编辑
    saveFlag: {
      required: false,
      type: Boolean,
      default: () => {
        return false;
      },
    },
    flag: {
      required: false,
      type: String,
      default: () => {
        return undefined;
      },
    },
  },
  data() {
    return {
      local: zh_cn,
      dictData: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      tabList: [
        {name: "基本信息", key: "baseInfo"},
        {name: "媒体信息", key: "mediaInfo"},
      ],
      tabKey: "baseInfo",
      formData: {
        b02VOList: [],
      },
      modalTitle: "",
      b0119Data: [],
      b0120Data: [],
      sqData: [],
      jdData: {},
      jdDataArray: [],
      zoomSize: 12,
      massMarks: "",
      areaMap: null,
      isFirstLoad:true,//是否第一次渲染地图
    };
  },
  created() {
    this.init();
  },
  mounted() {
    console.log(this.tabKey)
    this.$nextTick(()=>{
      this.initMap()
    })
  },
  beforeDestroy() {
    // 销毁地图
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    handleChangeB0122(orgId, option) {
      this.jdDataArray = this.jdData[orgId];
      for (const item of option) {
        if (item.orgId === orgId) {
          this.formData.b0107 = item.orgName;
          break;
        }
      }
    },
    handleChangeB0123(orgId, option) {
      for (const item of option) {
        if (item.orgId === orgId) {
          this.formData.b0108 = item.orgName;
          break;
        }
      }
    },
    init() {
      const params = {};
      params.dictFields = "B0106,B0113,B0114,B0115,B0117,B0118,B0129,B0133,B1106,B1109,B1113";
      this.$http.post(getBatchDict, params).then((res) => {
        this.dictData = res.result
      });
      this.$http.post(getDictCondition, {dictField: 'B0105',classify: this.classify}).then(res => {
        this.$set(this.dictData, 'B0105', res.result)
      })
      this.$http.post(getDictCondition, {dictField: 'B0104',classify: this.classify}).then(res => {
        this.$set(this.dictData, 'B0104', res.result)
      })
      this.getData();
      this.$http.post(getSQAndJD, {}).then((res) => {
        this.sqData = res.result.sqData;
        this.jdData = res.result.jdData;
        if (this.formData && this.formData.b0122) {
          this.jdDataArray = this.jdData[this.formData.b0122];
        }
      });
    },
    getData() {
      if (this.b0101) {
        this.$nextTick(() => {
          this.$http.post(getPointInfo, {b0101: this.b0101}).then((res) => {
            this.formData = res.result;
            this.handleTabClick("baseInfo");
          });
        });
      } else {
        this.handleTabClick("baseInfo");
      }
    },
    handleTabClick(key) {
      this.tabKey = key;
      if (key === "baseInfo") {
        //基本信息
        this.$nextTick(() => {

        });
      } else if (key === "mediaInfo") {
        //媒体信息
        this.$nextTick(() => {
          this.$refs.mediaInfoRef.editFlag = this.saveFlag;
          if (
              !this.formData.b02VOList ||
              this.formData.b02VOList.length === 0
          ) {
            this.formData.b02VOList = [];
          }
          this.$refs.mediaInfoRef.mediaInfoList = this.formData.b02VOList;
        })
      }
    },
    saveOrUpdate() {
      return new Promise((resolve, reject) => {
        const formData = JSON.parse(JSON.stringify(this.formData))
        formData.b02VOList = []
        formData.b03VOList = []
        if (this.$refs.mediaInfoRef) {
          this.$refs.mediaInfoRef.mediaInfoList.forEach((item) => {
            if (item.flag) {
              formData.b02VOList.push(item);
            }
          });
          this.$refs.mediaInfoRef.mediaInfoListForDel.forEach((item) => {
            if (item.flag) {
              formData.b02VOList.push(item);
            }
          });
        }
        resolve(formData);
      });
    },
    initMap() {
      AMapLoader.load({
        key: "e38ea4dfc12f0fd7864f078c6ce7b48d", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Marker",
          "AMap.Pixel",
          "AMap.DistrictSearch",
          "AMap.Autocomplete", // 输入提示插件
          "AMap.PlaceSearch", // POI搜索插件
          "AMap.Scale", // 右下角缩略图插件 比例尺
          "AMap.OverView", // 地图鹰眼插件
          "AMap.ToolBar", // 地图工具条
          "AMap.MapType", // 类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
          "AMap.PolyEditor", // 编辑 折线多，边形
          "AMap.CircleEditor", // 圆形编辑器插件
          "AMap.Geolocation", // 定位控件，用来获取和展示用户主机所在的经纬度位置
          "AMap.Geocoder",
        ],
      })
          .then((AMap) => {
            window.AMap = AMap;
            if (this.formData.b0111 && this.formData.b0112) {
              this.convertGps(this.formData.b0111, this.formData.b0112).then(() => {
                this.renderMap(true);
              });
            } else {
              this.renderMap(false);
            }
          })
          .catch((e) => {
            console.log(e);
          });
    },
    // WGS84坐标系(精度小于10米同国家2000坐标系) 转换成高德坐标系
    convertGps(longitude, dimension, type) {
      return new Promise((resolve, reject) => {
        AMap.convertFrom(
            [longitude, dimension],
            "gps",
            (status, result) => {
              if (status == "complete") {
                let lnglats = result.locations[0];
                if (type === 'b0125') {
                  this.$set(this.formData, "gpsLongitude_b0126", lnglats.lng);
                  this.$set(this.formData, "gpsLatitude_b0127", lnglats.lat);
                } else {
                  this.$set(this.formData, "gpsLongitude", lnglats.lng);
                  this.$set(this.formData, "gpsLatitude", lnglats.lat);
                }
                resolve();
              } else {
                reject();
                this.$message.error("坐标转换失败，请联系管理员！");
              }
            }
        );
      });
    },
    // 高德坐标系 转换成 WGS84坐标系(精度小于10米同国家2000坐标系)
    convertGcj() {
      let wgsArr = gcj02towgs84(
          this.formData.gpsLongitude,
          this.formData.gpsLatitude
      );
      if (!this.isFirstLoad){
        this.$set(this.formData, "b0111", wgsArr[0]);
        this.$set(this.formData, "b0112", wgsArr[1]);
      }
    },

    // 渲染地图
    renderMap(flag) {
      this.map = new AMap.Map("gssp", {
        resizeEnable: true,
        zoom: this.zoomSize, //初始化地图级别
        center: [
          this.formData.gpsLongitude || 120.699279,
          this.formData.gpsLatitude || 27.993849,
        ], //初始化地图中心点位置
      });
      this.map.setDefaultCursor("pointer");
      this.map.on("click", (e) => {
        this.formData.gpsLongitude = e.lnglat.getLng();
        this.formData.gpsLatitude = e.lnglat.getLat();
        this.isFirstLoad=false
        this.convertGcj();
        this.pickUp();
      });
      if (flag) {
        if (this.formData.b0109) {
          this.setPoint();
        } else {
          this.pickUp();
        }
      } else {
        // 没有经纬度，但是有地址的时候
        if (this.formData.b0109) {
            this.queryTude();
        }
      }
      var text = new AMap.Text({ //添加文字点标记
        map: this.map,
        // position: [120.6313, 28.0208], //基点位置
        draggable: false, //是否可拖动
        offset:[900,0],//偏移量
        content: '<div style="border:1px solid #ccc;background:#fff;white-space:nowrap; padding:3px;font-size:14px;">请在地图上选择点位落点</div>' //自定义点标记覆盖物内容
      });

      this.map.add(text)
    },

    // 地址-查询
    queryTude(val) {
      //如果点击重新定位
      if (val==='isClick'){
        this.isFirstLoad=false
      }
      if (!this.formData.b0109) {
        this.$message.error("请输入详细地址");
        return;
      }
      const autoOptions = {
        city: "0577", // 兴趣点城市
        citylimit: true, //是否强制限制在设置的城市内搜索
      };
      const geoLngLat = new AMap.Geocoder(autoOptions);
      geoLngLat.getLocation(this.formData.b0109, (status, result) => {
        if (status === "complete" && result.geocodes.length) {
          let lnglat = result.geocodes[0].location || {};
          this.$set(this.formData, "gpsLongitude", lnglat.lng);
          this.$set(this.formData, "gpsLatitude", lnglat.lat);
          this.convertGcj();
          this.setPoint();
        } else {
          this.$message.error("根据地址查询位置失败");
        }
      });
    },
    // 经纬度-拾取
    pickUp() {
      if (!this.formData.b0111) {
        this.$message.error("请输入经度或重新定位后选择");
        return;
      }
      if (!this.formData.b0112) {
        this.$message.error("请输入纬度度或重新定位后选择");
        return;
      }
      this.convertGps(this.formData.b0111, this.formData.b0112).then(() => {
        const geoOptions = {
          city: "0577", // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          radius: 1000,
        };
        const geocoder = new AMap.Geocoder(geoOptions);
        geocoder.getAddress(
            [this.formData.gpsLongitude, this.formData.gpsLatitude],
            (status, result) => {
              if (status === "complete" && result.regeocode) {
                let b0109 = result.regeocode.formattedAddress;
                this.$set(this.formData, "b0109", b0109);
                this.setPoint();
              } else {
                this.$message.error("根据经纬度查询地址失败");
              }
            }
        );
      });
    },
    // 原经纬度-拾取
    pickUpB0125() {
      if (!this.formData.b0126) {//原经度
        return;
      }
      if (!this.formData.b0127) {//原纬度
        return;
      }
      this.convertGps(this.formData.b0126, this.formData.b0127, 'b0125').then(() => {
        const geoOptions = {
          city: "0577", // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          radius: 1000,
        };
        const geocoder = new AMap.Geocoder(geoOptions);
        geocoder.getAddress(
            [this.formData.gpsLongitude_b0126, this.formData.gpsLatitude_b0127],
            (status, result) => {
              if (status === "complete" && result.regeocode) {
                let b0125 = result.regeocode.formattedAddress;
                this.$set(this.formData, "b0125", b0125);
                this.setPoint();
              } else {
                this.$message.error("根据原经纬度查询留档地址失败");
              }
            }
        );
      });
    },

    // 安放点位
    setPoint() {
      if (this.massMarks) {
        this.massMarks.setData([]);
        // this.massMarks.setMap(null);
        // this.massMarks.clear()
      }
      var styleObject = [{
        //url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
        url: require("@/assets/img/icon-pointLiu.png"),  // 图标地址
        //anchor: new AMap.Pixel(50, 50),
        anchor:'bottom-center', // 设置锚点方位

        size: new AMap.Size(100, 100),
        // zIndex: 每种样式图标的叠加顺序，数字越大越靠前
        zIndex: 99,
      }, {
        url: require("@/assets/img/icon-point.png"),  // 图标地址
        size: new AMap.Size(60, 60),      // 图标大小
        // anchor: new AMap.Pixel(-20, -20),// 图标显示位置偏移量，基准点为图标左上角
        anchor:'bottom-center', // 设置锚点方位
        zIndex: 10,
      }]
      this.massMarks = new AMap.MassMarks(null, {
        zIndex: 2,  // 海量点图层叠加的顺序
        zooms: [0, 30],  // 在指定地图缩放级别范围内展示海量点图层
        style: styleObject  // 设置样式对象
      });
      var data = []
      if (this.formData.gpsLongitude_b0126 === undefined || this.formData.gpsLatitude_b0127 === undefined) {
        this.pickUpB0125();
      }
      if (this.formData.gpsLongitude === undefined
          || this.formData.gpsLatitude === undefined) {
        data = []
      } else if (this.formData.gpsLongitude_b0126 === undefined
          || this.formData.gpsLatitude_b0127 === undefined) {
        data = [{
          lnglat: [this.formData.gpsLongitude, this.formData.gpsLatitude], //点标记位置
          name: 'b0109',
          style: 1, // 该数据的样式取值styleObjectArr对应的样式索引
          id: 1
        },];
      } else {
        data = [{
          lnglat: [this.formData.gpsLongitude, this.formData.gpsLatitude], //点标记位置
          name: 'b0109',
          style: 1, // 该数据的样式取值styleObjectArr对应的样式索引
          id: 1
        }, {
          lnglat: [this.formData.gpsLongitude_b0126, this.formData.gpsLatitude_b0127], //点标记位置
          name: 'b0125',
          style: 0, // 该数据的样式取值styleObjectArr对应的样式索引
          id: 2
        },
        ];
      }
      this.massMarks.setData(data);
      // 将海量点添加至地图实例
      this.massMarks.setMap(this.map);
      this.zoomSize = 15;
      this.map.setZoom(this.zoomSize);
      this.map.setCenter(
          [this.formData.gpsLongitude, this.formData.gpsLatitude,]
      );
    },
    // 地图-放大
    checkEnlarge() {
      this.map.setZoom((this.zoomSize += 1));
    },
    // 地图-缩小
    checkNarrow() {
      if (this.zoomSize > 8) {
        this.map.setZoom((this.zoomSize -= 1));
      }
    },
  },
  watch: {
    formData() {
      this.$nextTick(() => {
        //此时就可以获取到在created赋值后的dataList了
        this.initMap();

      });
    },
  },

};
</script>
<style lang="less" scoped>
.map-box {
  position: relative;
  height: 600px;
  padding-left: 20px;

  #gssp {
    height: 100%;
  }

  #area {
    height: 100%;
  }

  .scale {
    position: absolute;
    top: 20px;
    left: 40px;
    width: 30px;
    height: 80px;
    display: flex;
    flex-direction: column;

    p {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #dfdfdf;
      background: #fff;
      font-size: 22px;
      color: #49bbeb;
      cursor: pointer;

      &:first-child {
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
      }

      &:last-child {
        border-top: none;
        border-bottom-left-radius: 3px;
        border-bottom-right-radius: 3px;
      }

      &:hover {
        background: #f2f2f2;
      }
    }
  }
}
.r-wrap {
  width: 100%;
  //padding: 20px;
  box-sizing: border-box;

  .r-nav {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-top: 2vh;

    li {
      flex: 0 0 auto;
      width: 102px;
      height: 32px;
      line-height: 32px;
      margin-left: 20px;
      background: url("@/assets/img/dialog-selected.svg") no-repeat;
      background-size: 102px 32px;
      text-align: center;
      font-size: 16px;
      cursor: pointer;
      color: #fff;

      &.active {
        color: red;
        background: url("@/assets/img/dialog-unselect.svg") no-repeat;
      }
    }
  }

  .r-content {
    height: 68vh;
    margin-top: 2vh;
    overflow: auto;
  }

  .tabs-box {
    .tabs-item {
      margin-right: 20px;
    }
  }
}
</style>
